package org.chronologger.poppaea.client.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.chronologger.poppaea.client.utils.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class ChronologyData implements Serializable {
	static ChronologyServiceAsync service = null;

	private static final long serialVersionUID = 1L;

	@NotPersistent
	public List<Location> locations;

	@NotPersistent
	public List<Person> characters;

	@NotPersistent
	public Date startTime;

	@NotPersistent
	public Date endTime;

	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Long id;

	@Persistent
	private String name;

	public ChronologyData() {
		locations = new ArrayList<Location>();
		characters = new ArrayList<Person>();
	}

	static ChronologyServiceAsync getService() {
		if (service == null)
			service = GWT.create(ChronologyService.class);
		return service;
	}

	public static void createNew(String name,
			AsyncCallback<ChronologyData> callback) {
		getService().createChronology(name, callback);
	}

	public static void getById(Long id, AsyncCallback<ChronologyData> callback) {
		getService().getChronology(id, callback);
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	protected void setId(Long id) {
		this.id = id;
	}

	public Long getId() {
		return id;
	}

	public Location addLocation() {
		final Location newLocation = new Location();
		locations.add(newLocation);
		newLocation.setChronologyId(this.getId());
		
		getService().addLocation(getId(), new AsyncCallback<Location>() {

			public void onSuccess(Location result) {
				newLocation.setId(result.getId());
			}

			public void onFailure(Throwable caught) {
				Logger.error("Couldn't create location");
			}
		});
		return newLocation;
	}

}